/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.tutotec.conf;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Acacio
 */
public class ConfigFile {

	//private static final String ARQUIVO = "config.properties";
	private static final String ARQUIVO = "config.xml";
	
    private Properties prop;
    private InputStream input;
    private boolean carregado;
   

	public ConfigFile() {
    
    	this.prop = new Properties();
    	
    	this.carregado = false;
        
    }
    
	protected void Load(){
		
		try {
            File f = new File(ARQUIVO);
            if(!f.exists()){
                f.createNewFile();
                prop.storeToXML(new FileOutputStream(f), null);
            }
            
            input = new FileInputStream(f);
            
            try{
            	prop.loadFromXML(input);
            }catch(InvalidPropertiesFormatException e){
            	prop.storeToXML(new FileOutputStream(f), null);
            }
            
            
            this.carregado = true;
            
        } catch (IOException ex) {
            Logger.getLogger(ConfigFile.class.getName()).log(Level.SEVERE, null, ex);
        }
		
		
	}
    
	protected void Save(){
		
		try {
            File f = new File(ARQUIVO);
            prop.storeToXML(new FileOutputStream(f), null);
            
            
        } catch (IOException ex) {
            Logger.getLogger(ConfigFile.class.getName()).log(Level.SEVERE, null, ex);
        }
		
		
	}
	
	public String getString(String Key, String Default){
		if(this.carregado)
			return this.prop.getProperty(Key, Default);
		return Default;		
	}

	
	public int getInteger(String Key, int Default){
		return Integer.valueOf(this.getString(Key, String.valueOf(Default)));
	}
 

	public boolean getBoolean(String Key, boolean Default){
		return Boolean.valueOf(this.getString(Key,  (Default?"true":"false") ));		
	}
	
	public long getLong(String Key, long Default){
		return Long.valueOf(this.getString(Key, String.valueOf(Default) ));
	}
	
	
	

	public void setString(String Key, String Valor){
		if(this.carregado)
			this.prop.setProperty(Key, Valor);
	}
	
	public void setInteger(String Key, int Valor){
		this.setString(Key, String.valueOf(Valor));
	}
	
	public void setBoolean(String Key, boolean Valor){
		this.setString(Key, String.valueOf(Valor));
	}
	
	public void setLong(String Key, long Default){
		this.setString(Key, String.valueOf(Default) );
	}
	
	
}
